	
	// Hien thi ban be Yahoo len danh sach ban be cua giao dien
	function addContactYahoo(username)
	{
		var img = "<img src='http://img.msg.yahoo.com/avatar.php?yids=#{label}' width='25' height='25'/>";
		var tabTemplate = "<li><a href='#'>" + img + "<span style='position:relative; left: 5px; bottom:5px'>#{label}</span></a>" +
						"<ul>" +
							"<li><a href='javascript:void(0);'><img src='img/chat.png' alt='chat' /> Chat</a></li>" +
						"</ul>" +
					   "</li>";
		var friend = $(tabTemplate.replace( /#\{label}/g, username));
		$('#list').append(friend);		
	}
	
	
	// Hien thi ban be Ajax len danh sach ban be cua giao dien
	function addContactAjax(username)
	{
		var img = "<img src='http://localhost:53220/api/avatar?username=#{username}' width='25' height='25'/>";	
		var tabUserTemplate = "<li><a href='#'>" + img + "<span style='position:relative; left: 5px; bottom:5px'>#{label}</span></a>" +
							"<ul>" +
								"<li><a href='javascript:void(0);'><img src='img/chat.png' alt='chat' /> Chat</a></li>" +
								"<li><a href='javascript:void(0)'><img src='img/add.png' alt='add' /> Delete</a></li>" +
							"</ul>" +
						   "</li>";
		var friend = $(tabUserTemplate.replace( /#\{label\}/g, username).replace( /#\{username\}/g, username));
		$('#list').append(friend);				   
	}

// Lay danh sach ban be Ajax
function recvFriendsAjax()
	{
		var requestURL = "http://localhost:53220/api/friendlist?user=" + $('#select').text();
		$.ajax({
		    url: requestURL,
		    type: 'GET',
		    success: function (data) {
		        if (data != null) {
		            $.each(data, function (key, val) {
		                var newContact = 1;
		                $("#list a").each(function (i) {
		                    if (this.text == val.Username) {
		                        if (val.IsOnl == 0)
		                            $(this).closest("li").addClass('ui-state-disabled');
		                        else
		                            $(this).closest("li").removeClass('ui-state-disabled');
		                        newContact = 0;
		                        return true;
		                    }
		                });
		                if (newContact == 1) {
		                    addContactAjax(val.Username);
		                    playSound('sound/online.wav');
		                }
		            });
		            $('#list').menu('refresh');
		        }
		    }
		});
	}
	//Lay danh sach ban be Yahoo
	function recvFriendsYahoo()
	{
		var requestURL = "http://localhost:53220/api/yahoofriends?oauth_token=" + $('#oauth_token').text() + "&oauth_token_secret=" + $('#oauth_token_secret').text() + "&sessionID=" + $('#sessionID').text();
		$.ajax({
			url: requestURL,
			type: 'GET',
			success: function(data){
				 $.each(data, function (key, val){
					$("#list a").each(function(i){
					if(this.text == val.Username)
					{
						if(val.IsOnl == 0)
							$( this ).closest( "li" ).addClass('ui-state-disabled');
						else
							$( this ).closest( "li" ).removeClass('ui-state-disabled');
						return true;
					}				
				});
					
					});
			}		
			});
	}
	$(document).ready(function () {
	    var login = false;
	    jQuery.support.cors = true;

	    //Dang nhap thanh cong, hien thi giao dien
	    function ShowMainGui() {
	        $('#login').hide().css({ 'left': '0px' });
	        $('#Login_form').hide().css({ 'top': '0px' });
	        $('#content').css('opacity', '1');
	        $('#footer').css('opacity', '1');
	        $('#profile').css('opacity', '1');
	        $('#select').button({ icons: { primary: "ui-icon-triangle-1-s"} });
	        $('#log').hide();
	    }



	    // Lay danh sach ban be va hien thi.
	    function GetFriendList() {

	        if ($('#typeChat option:selected').text() == 'Ajax chat') {
	            var requestURL = "http://localhost:53220/api/friendlist?user=" + $('#select').text();
	            $.getJSON(requestURL, function (data) {
	                $.each(data, function (key, val) {
	                    addContactAjax(val.Username);
	                });
	                $('#list').menu();
	                recvFriendsAjax();
	                // Cap nhat trang thai ban be Ajax	
	                setInterval('recvFriendsAjax()', 10000);
	            });

	        }
	        else {
	            var requestURL = "http://localhost:53220/api/yahoofriends?oauth_token=" + $('#oauth_token').text() + "&oauth_token_secret=" + $('#oauth_token_secret').text() + "&sessionID=" + $('#sessionID').text();
	            $.getJSON(requestURL, function (data) {
	                $.each(data, function (key, val) {
	                    addContactYahoo(val.Username);
	                });
	                $('#list').menu();

	            });
	            recvFriendsYahoo();
	            //Cap nhat trang thai ban be Yahoo
	            setInterval('recvFriendsYahoo()', 10000);
	        }
	    }


	    $("#login").click(function () {
	        var username = $('#edit-name').val();
	        var pass = $('#edit-pass').val();
	        if ($('#typeChat option:selected').text() == 'Ajax chat') {
	            var requestURL = "http://localhost:53220/api/Account?username=" + username + "&pass=" + pass;
	            $.getJSON(requestURL, function (data) {
	                if (data != null) {
	                    $('#select').text($('#edit-name').val());
	                    alert($('#edit-name').val());
	                    ShowMainGui();
	                    GetFriendList();
	                    recvMessAjax();
	                    setInterval('requestFriend()', 10000);
	                }
	                else {
	                    alert("Account is invalid!");
	                }
	            })
			.fail(function (jqXHR, textStatus, err) {
			    alert('Error ' + err);
			});
	        }
	        else {
	            var requestURL = "http://localhost:53220/api/yahoologin?username=" + username + "&passwd=" + pass;
	            $.ajax({
	                url: requestURL,
	                type: 'GET',
	                success: function (data) {
	                    if (data != null) {
	                        $('#select').text($('#edit-name').val());
	                        var obj = data.split(',');
	                        $('#oauth_token').text(obj[0].split(':')[1]);
	                        $('#oauth_token_secret').text(obj[1].split(':')[1]);
	                        $('#sessionID').text(obj[2].split(':')[1]);
	                        $('#primaryLoginID').text(obj[3].split(':')[1]);
	                        $('#notifyServer').text(obj[4].split(':')[1]);
	                        ShowMainGui();
	                        GetFriendList();
	                        recvMessYahoo();
	                    }
	                    else {
	                        alert("Account is invalid!");
	                    }
	                },
	                error: function () { alert('Error'); }
	            });
	        }
	    });
	    $('#submit').click(function () {
	        if ($('#submit-pass').val().trim() == $('#submit-confirm-pass').val().trim() && $('#typeChat option:selected').text() == 'Ajax chat') {
	            var account = new Object();
	            account.ID = 1;
	            account.UserName = $('#submit-name').val(),
			account.Pass = $('#submit-pass').val();
	            var requestURL = "http://localhost:53220/api/account";
	            $.ajax({
	                url: requestURL,
	                type: "POST",
	                dataType: 'json',
	                accept: "application/json",
	                data: account,
	                success: function (data) {
	                    if (data > -1) {
	                        $('#select').text($('#submit-name').val());
	                        $('#list').menu();
	                        ShowMainGui();
	                        GetFriendList();
	                        recvMessAjax();
	                        setInterval('requestFriend()', 10000);
	                    }
	                    else
	                        alert("Account is exist!");
	                },
	                error: function (data) {
	                    alert("Error! Please try again!");
	                }
	            });
	        }
	        else {
	            //$('#acceptFriendDialog').dialog('open');
	            alert("Password and Confirm password not match or Not support");
	        }
	    });

	    $("#logout").click(function () {
	        Logout();
	    });
	    function Logout() {
	        if ($('#select').text() != 'TEST') {
	            if ($('#typeChat option:selected').text() == 'Ajax chat') {
	                var requestURL = "http://localhost:53220/api/account?username=" + $('#select').text();
	                $.ajax({
	                    url: requestURL,
	                    type: 'DELETE',
	                    success: function (data) {
	                        location.reload();
	                    }
	                });
	            }
	            else {
	                var requestURL = "http://localhost:53220/api/yahoologin?oauth_token=" + $('#oauth_token').text() + "&oauth_token_secret=" + $('#oauth_token_secret').text() + "&sessionID=" + $('#sessionID').text();
	                $.ajax({
	                    url: requestURL,
	                    type: 'DELETE',
	                    success: function (data) {
	                        location.reload();
	                    }
	                });
	            }
	        }
	    }
	    window.onbeforeunload = function (e) {
	        var e = e || window.event;
	        if (e) {
	            e.returnValue = ' ';
	        }
	        return ' ';
	    };
	    window.onunload = function () {
	        Logout();
	    };
	});
